#include "head.h"

int cmd_anal(const char *buf, int buf_length, cmd_t *pCmd)
{                            // 解析命令字符串，并根据命令类型给token赋值
    char temp[3][256] = {0}; // 用于存放输入命令中的各个词块
    int i = 0, j = 0;
    for (int k = 0; k < buf_length; ++k)
    {
        if (buf[k] != ' ' && buf[k] != '\n')
        {
            temp[i][j++] = buf[k];
        }
        else if (buf[k] == ' ')
        {
            if (buf[k - 1] != ' ' && k != 0)
            {
                ++i;
                j = 0;
            }
            if (i >= 2)
            {
                printf("too many arguments\n");
                return -1;
            }
        }
        else if (buf[k] == '\n')
        {
            break;
        }
        else
        {
            printf("ERROR COMMAND!\n");
            return -1;
        }
    }
    // 判断temp[0]中存储的字符串是不是合法命令，若是则将其对应枚举值存入cmd结构体，否则则报错
    pCmdWord pCur = HashTable[elf_hash(temp[0])];
    if (pCur != NULL && strcmp(pCur->str, temp[0]) == 0)
    {
        pCmd->token = pCur->token;
    }
    else
    {
        printf("ERROR COMMAND!\n");
        return -1;
    }
    strcpy(pCmd->object, temp[1]);
    // printf("pCmd->object[%d] = %s\n",k,pCmd->object[k]);
    return 0;
}

int isunfinished(cmd_t Cmd)
{ // 判断是否存在未完全传送的文件
    char buf[1024] = {0};
    sprintf(buf, "./download");
    DIR *dir = opendir(buf);
    struct dirent *pdirent;
    strcat(Cmd.object, ".filepart");
    while ((pdirent = readdir(dir)) != NULL)
    {
        if (strcmp(Cmd.object, pdirent->d_name) == 0)
        {
            return 1;
        }
    }
    return 0;
}

off_t get_offset(char *fileName)
{ // 返回已传送大小
    strcat(fileName, ".filepart");
    char path[1000] = {0};
    sprintf(path, "download/%s", fileName);
    int fd = open(path, O_RDWR);
    ERROR_CHECK(fd, -1, "open");
    struct stat *buf = (struct stat *)calloc(1, sizeof(struct stat));
    fstat(fd, buf);
    // printf("buf->st_size = %ld\n",buf->st_size);
    return buf->st_size;
}
